<template>
  <div>
    <div>
      <el-steps class="forgot-steps" :active="active" finish-status="success" align-center>
        <el-step class="forgot-step" title="验证电子邮件"/>
        <el-step class="forgot-step" title="重新设置密码"/>
      </el-steps>
    </div>
    <transition name="el-fade-in-linear" mode="out-in">
      <div class="forgot-page" v-if="active === 0">
        <div class="forgot-title">
          <div class="forgot-title-child1th" contenteditable="false">重置密码</div>
          <div class="forgot-title-child2th">请输入需要重置密码的电子邮箱</div>
        </div>
        <div class="forgot-form">
          <el-form :model="form" :rules="rules" @validate="onValidate" ref="formRef">
            <el-form-item prop="email">
              <el-input v-model="form.email" type="text" placeholder="电子邮箱地址">
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item class="forgot-email" prop="code">
              <el-row :gutter="10">
                <el-col :span="17">
                  <el-input v-model="form.code" maxlength="6" type="text" placeholder="请输入验证码">
                    <template #prefix>
                      <el-icon><EditPen /></el-icon>
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="5">
                  <el-button class="forgot-email-button" @click="validateEmail" :disabled="!isEmailValid || refreshTime > 0">
                    {{refreshTime > 0 ? '剩余' + refreshTime + '秒' : '获取验证码'}}
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </div>
        <el-link class="forgot-login-link" @click="router.push('/')">不改了</el-link>
        <div class="forgot-forgot">
          <el-button @click="forgotPassword()" class="forgot-forgot-button1th" type="warning" plain>下一步</el-button>
        </div>
      </div>
    </transition>
    <transition name="el-fade-in-linear" mode="out-in">
      <div class="forgot-page" v-if="active === 1">
        <div class="forgot-title">
          <div class="forgot-title-child1th" contenteditable="false">重置密码</div>
          <div class="forgot-title-child2th">请填写新密码</div>
        </div>
        <div class="forgot-form">
          <el-form :model="form" :rules="rules" @validate="onValidate" ref="formRef">
            <el-form-item prop="password">
              <el-input v-model="form.password" maxlength="15" type="password" placeholder="新密码">
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password_repeat">
              <el-input v-model="form.password_repeat" maxlength="15" type="password" placeholder="确认新密码">
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="forgot-forgot">
          <el-button @click="doForgot()" class="forgot-forgot-button1th" type="warning" plain>确认重置密码</el-button>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>

import {reactive, ref} from "vue";
import {EditPen, Lock, Message} from "@element-plus/icons-vue";
import {post} from "@/api/request.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
const formRef = ref()
const isEmailValid = ref(false)
const refreshTime = ref(0)
const active = ref(0)
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms))
const onValidate = (prop, isValid) => {
  if (prop === 'email')
    isEmailValid.value = isValid
}

const form = reactive({
  email: '',
  code: '',
  password: '',
  password_repeat: ''
})

const validatePasswordRepeat = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.password) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}
const validateEmail = () => {
  refreshTime.value = 60
  post('api/auth/valid-forgot-email', {
    email: form.email
  }, (message) => {
    ElMessage.success(message)
    setInterval(() => refreshTime.value--, 1000) // 每秒减1
  }, (message) => {
    refreshTime.value = 0
    ElMessage.warning(message)
  })
}

const forgotPassword = () => {
  formRef.value.validate((isValid) => {
    if (isValid) {
      post('/api/auth/forgot', {
        email: form.email,
        code: form.code
      }, () => {
        active.value++;
      })
    } else {
      ElMessage.warning("请填写完整正确信息")
    }
  })
}
const doForgot = () => {
  formRef.value.validate((isValid) => {
    if (isValid) {
      post('/api/auth/do-forgot', {
        password: form.password
      }, async (message) => {
        ElMessage.success(message)
        active.value++;
        await sleep(3000);
        await router.push('/')
      })
    } else {
      ElMessage.warning("请填写完整正确信息")
    }
  })
}
const rules = {
  email: [
    { required: true, message: '请输入邮件地址', trigger: ['blur', 'change'] },
    { type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change'] }
  ],
  code: [
    { min: 6, max: 6, required: true, message: '请输入验证码', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
    { min: 6, max: 15, message: '密码的长度必须在6-15个字符之间', trigger: ['blur', 'change'] }
  ],
  password_repeat: [
    { validator: validatePasswordRepeat, trigger: ['blur', 'change'] }
  ]
}

</script>

<style scoped>
  @import "@/assets/css/welcome/forgot-password-page.scss";
</style>